package com.example.healkepdoctor.View.patientInfo;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.pm.Attribution;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.MenuItem;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.example.healkepdoctor.R;
import com.example.healkepdoctor.View.patientInfo.helper.patientInfoHelper;
import com.example.healkepdoctor.model.Weight;
import com.example.healkepdoctor.model.patientInfo;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;

public class patientInfoDetailActivity extends AppCompatActivity {
    private patientInfo info;
    private TableLayout table;
    private Weight weight;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_patient_info_detail);
        Intent intent = getIntent();
        if(intent == null) finish();
        Bundle bundle = intent.getBundleExtra("info");
        info = bundle.getParcelable("patient");
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null){
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setTitle("详细信息");
        }
        patientInfoHelper helper = new patientInfoHelper(new WeightHandler());
        helper.getWeight(info.getUsername());
    }
    private void initComponent(){
        table = findViewById(R.id.table);
        creatTable(table);
    }

    class WeightHandler extends Handler{

        @Override
        public void handleMessage(@NonNull Message msg) {
            if(msg.what == patientInfoHelper.SUCCESS){
                weight = msg.getData().getParcelable("weight");
                initComponent();
            }else if(msg.what == patientInfoHelper.FAILED){
                Toast.makeText(patientInfoDetailActivity.this, "未知错误",Toast.LENGTH_SHORT).show();
                finish();
            }else{
                Toast.makeText(patientInfoDetailActivity.this, "网络异常",Toast.LENGTH_SHORT).show();
            }
        }
    }
    private void creatTable(TableLayout root){
        float titleSize = 24;
        float size = 16;
        int now = 1;
        int margin = 3;
        LocalDate start;
        String preWeek;
        if(info.getDate()!=null){
            try{
                start = LocalDate.parse(info.getDate());
            }catch (DateTimeParseException e){
                start = LocalDate.parse(info.getDate(), DateTimeFormatter.ofPattern("yyyy-M-d"));
            }
            LocalDate end = LocalDate.now();
            long week = ChronoUnit.WEEKS.between(start,end);
            preWeek = String.valueOf(week);
        }else{
            preWeek = "Unknown";
        }
        double beforeBMI = info.getWeight1()/(info.getHeight1()/100)/(info.getHeight1()/100);
        String beforeBMIstr = String.format("%.2f",beforeBMI);

        int speed = 1;
        int bmiIndex = 0;
        double rate = (weight.getWeight()-info.getFfm())/weight.getWeight();
        String rateStr = String.format("%.2f",rate);
        if(beforeBMI<18)
            bmiIndex = 1;
        else if(beforeBMI>=18 && beforeBMI<24){
            bmiIndex = 2;
        }else{
            bmiIndex = 3;
        }
        String[][] str = {
                {"孕妇信息表"},
                {"姓名",info.getClientName(),"年龄",String.valueOf(LocalDate.now().getYear()-info.getBirth()+1)},
                {"怀孕日期",info.getDate(),"孕周",preWeek},
                {"身高",String.valueOf(info.getHeight1()),"妊娠胎数",info.getNum()},
                {"孕前体重",String.valueOf(info.getWeight1()),"当前体重",String.valueOf(info.getWeight1())},
                {"孕前BMI",beforeBMIstr+"("+bmiIndex+")","生长速度",String.valueOf(speed)},
                {"体脂百分比",rateStr,"去脂体重",String.valueOf(info.getFfm())},
                {"肌肉含量",String.valueOf(info.getMuscle()),"蛋白质含量",String.valueOf(info.getProtein())},
                {"估计的24hUCrE",String.valueOf(info.getUcre())},
                {"疾病史"},
                {info.getDiseases()}
        };
        int rowNum = str.length;
        while(now<=rowNum){
            TableRow row = new TableRow(this);
            row.setBackgroundColor(getColor(R.color.black));
            List<TextView> sons = new ArrayList<>();
            if(now==1){//Title
                TextView title = new TextView(this);
                title.setText(str[now-1][0]);
                TableRow.LayoutParams params = new TableRow.LayoutParams();
                params.rightMargin = 3;
                title.setTextSize(titleSize);
                params.width = 0;
                params.height = TableRow.LayoutParams.MATCH_PARENT;
                params.weight = 1;
                title.setLayoutParams(params);
                sons.add(title);
            }else if(now>=2 && now<=8){
                TextView Lname = new TextView(this);
                TextView name = new TextView(this);
                TextView Lage = new TextView(this);
                TextView age = new TextView(this);
                Lname.setText(str[now-1][0]);
                name.setText(str[now-1][1]);
                Lage.setText(str[now-1][2]);
                age.setText(str[now-1][3]);
                List<TextView> temp = new ArrayList<>();
                temp.add(Lname);
                temp.add(name);
                temp.add(Lage);
                temp.add(age);
                int col = 0;
                for(TextView v:temp){
                    TableRow.LayoutParams params = new TableRow.LayoutParams();
                    params.column = col;
                    params.width = 0;
                    params.weight = 1;
                    params.height = TableRow.LayoutParams.MATCH_PARENT;
                    if(v == age)
                        params.rightMargin = margin;
                    v.setLayoutParams(params);
                    col++;
                }
                sons.addAll(temp);
            }else if(now == 9){
                TextView Lname = new TextView(this);
                TextView name = new TextView(this);
                Lname.setText(str[now-1][0]);
                name.setText(str[now-1][1]);
                List<TextView> temp = new ArrayList<>();
                temp.add(Lname);
                temp.add(name);
                int col = 0;
                for(TextView v:temp){
                    TableRow.LayoutParams params = new TableRow.LayoutParams();
                    params.column = col;
                    params.width = 0;
                    params.weight = 1;
                    params.height = TableRow.LayoutParams.MATCH_PARENT;
                    if(v == name)
                        params.rightMargin = margin;
                    v.setLayoutParams(params);
                    col++;
                }
                sons.addAll(temp);
            }else if(now ==10 ){
                TextView Lname = new TextView(this);
                Lname.setText(str[now-1][0]);
                List<TextView> temp = new ArrayList<>();
                temp.add(Lname);
                int col = 0;
                for(TextView v:temp){
                    TableRow.LayoutParams params = new TableRow.LayoutParams();
                    params.column = col;
                    params.width = 0;
                    params.weight = 1;
                    params.rightMargin = margin;
                    params.height = TableRow.LayoutParams.MATCH_PARENT;
                    v.setLayoutParams(params);
                    col++;
                }
                sons.addAll(temp);
            }else if(now == 11){
                TextView Lname = new TextView(this);
                Lname.setText(str[now-1][0]);
                List<TextView> temp = new ArrayList<>();
                temp.add(Lname);
                int col = 0;
                for(TextView v:temp){
                    TableRow.LayoutParams params = new TableRow.LayoutParams();
                    params.column = col;
                    params.width = 0;
                    params.weight = 1;
                    params.rightMargin = margin;
                    params.bottomMargin = margin;
                    params.height = TableRow.LayoutParams.MATCH_PARENT;
                    v.setLayoutParams(params);
                    col++;
                }
                sons.addAll(temp);
            }
            for(TextView tv : sons){
                TableRow.LayoutParams params = (TableRow.LayoutParams) tv.getLayoutParams();
                params.leftMargin = margin;
                params.topMargin = margin;
                tv.setGravity(Gravity.CENTER);
                tv.setTextColor(getColor(R.color.black));
                tv.setBackgroundColor(getColor(R.color.white));
                tv.setTextSize(size);
                row.addView(tv);
            }
            if(now == 1){
                sons.get(0).setTextSize(titleSize);
            }
            root.addView(row);
            now++;
        }

    }

    public boolean onOptionsItemSelected(MenuItem item) {
        //返回按钮点击事件
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}